
package com.hlkj.pay.controller.order;
/*
 * Hlpay-Plus aggregate payment system.
 * Copyright (c) 2024-2025 Hlpay Team Copyright has the right of final interpretation.
 */

import cn.hutool.core.date.DatePattern;
import com.hlkj.framework.common.pojo.CommonResult;
import com.hlkj.framework.common.pojo.PageResult;
import com.hlkj.framework.common.util.collection.CollectionUtils;
import com.hlkj.pay.app.common.IDownloadExcelService;
import com.hlkj.pay.app.order.IRefundOrderAppService;
import com.hlkj.pay.controller.BaseController;
import com.hlkj.pay.dto.order.RefundOrderQueryDto;
import com.hlkj.pay.enums.PayEnums;
import com.hlkj.pay.enums.PayOrderEnums;
import com.hlkj.pay.infrastructure.model.order.RefundOrderDO;
import com.hlkj.pay.infrastructure.model.pay.PayWayDO;
import com.hlkj.pay.service.order.IRefundOrderService;
import com.hlkj.pay.service.pay.IPayWayService;
import com.hlkj.pay.util.DateUtils;
import com.hlkj.pay.vo.order.req.OrderRefundApplyReq;
import com.hlkj.pay.vo.order.req.RefundOrderPageQueryReq;
import com.hlkj.pay.vo.order.req.RefundOrderParamReq;
import com.hlkj.pay.vo.order.resp.RefundOrderDetailResp;
import com.hlkj.pay.vo.order.resp.RefundOrderResp;
import com.hlkj.pay.vo.order.resp.export.RefundOrderFileExport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.mica.core.utils.BeanUtil;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author HlpayTeam
 * @date 2024/10/23 11:36
 */
@Tag(name = "订单退款管理")
@RestController
@RequestMapping("/v1/order/refund/")
@RequiredArgsConstructor
@Slf4j
public class RefundOrderController extends BaseController {

    private final IRefundOrderService refundOrderService;

    private final IRefundOrderAppService refundOrderAppService;

    private final IDownloadExcelService downloadExcelService;

    private final IPayWayService payWayService;

    @Operation(summary = "退款订单查询")
    @GetMapping("/page")
    CommonResult<PageResult<RefundOrderDetailResp>> queryRefundOrderPage(RefundOrderPageQueryReq refundOrderPageQueryReq) {
        RefundOrderQueryDto refundOrderQueryDto = BeanUtil.copy(refundOrderPageQueryReq, RefundOrderQueryDto.class);
        // if (refundOrderPageQueryReq.getType() != null &&
        // StringUtils.hasText(refundOrderPageQueryReq.getOrderNo())) {
        // // 1:平台订单号 2:商户订单号 3:机构订单号 4:渠道订单号 5:渠道附加订单号
        // switch (refundOrderPageQueryReq.getType()) {
        // case 1:
        // refundOrderQueryDto.setPayOrderNo(refundOrderPageQueryReq.getOrderNo());
        // break;
        // case 2:
        // refundOrderQueryDto.setMchOrderNo(refundOrderPageQueryReq.getOrderNo());
        // break;
        // case 3:
        // refundOrderQueryDto.setRefundOrderNo(refundOrderPageQueryReq.getOrderNo());
        // break;
        // case 4:
        // refundOrderQueryDto.setMchRefundOrderNo(refundOrderPageQueryReq.getOrderNo());
        // break;
        // }
        // }
        processQueryDate(refundOrderPageQueryReq, refundOrderQueryDto);
        // refundOrderQueryDto.setRefundOrderNo(null);
        // refundOrderQueryDto.setLikeRefundOrderNo(refundOrderPageQueryReq.getRefundOrderNo());
        PageResult<RefundOrderDO> page = refundOrderService.queryPage(refundOrderQueryDto);
        List<RefundOrderDO> list = page.getList();
        if (CollectionUtils.isEmpty(list)) {
            return buildPageResult(page, Collections.emptyList());
        }

        if (refundOrderPageQueryReq.getExport() == 1) {
            String fileName = refundOrderPageQueryReq.getExportName();
            if (!StringUtils.hasText(fileName)) fileName = "退款订单导出_" + DateUtils.getDateString(DatePattern.PURE_DATETIME_PATTERN);
            downloadExcelService.createExcel(fileName, refundOrderQueryDto, RefundOrderFileExport.class);
            return CommonResult.success();
        } else {
            List<RefundOrderDO> refundingList = list.stream().filter(refundOrderDO -> PayOrderEnums.REFUND_STATUS.REFUNDING.getCode().equals(refundOrderDO.getRefundStatus()))
                    .collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(refundingList)) {
                refundOrderAppService.queryRefundStatusList(refundingList);
            }
            List<RefundOrderDetailResp> refundOrderDetailRespList = cn.hutool.core.bean.BeanUtil.copyToList(list, RefundOrderDetailResp.class);
            processOrderList(refundOrderDetailRespList);
            List<String> payWayCodes = list.stream().filter(baseResp -> StringUtils.hasText(baseResp.getPayWayCode())).map(roleResp -> roleResp.getPayWayCode())
                    .collect(Collectors.toList());
            List<PayWayDO> payWayList = payWayService.queryByCodes(payWayCodes);
            Map<String, PayWayDO> payWayMap = payWayList.stream().collect(Collectors.toMap(payWayDO -> payWayDO.getCode(), Function.identity(), (t1, t2) -> t1));
            refundOrderDetailRespList.stream().forEach(roleResp -> {
                PayEnums.PAY_TYPE payType = PayEnums.PAY_TYPE.fromByCode(payWayMap.get(roleResp.getPayWayCode()).getType());
                roleResp.setPayType(payType.getType());
            });
            return buildPageResult(page, refundOrderDetailRespList);
        }
    }

    @Operation(summary = "退款订单详情")
    @GetMapping("/detail")
    CommonResult<RefundOrderDetailResp> queryRefundOrderDetail(@RequestParam("refundOrderNo") String refundOrderNo) {
        RefundOrderDO refundOrderDO = refundOrderService.queryRefundOrder(refundOrderNo);
        if (refundOrderDO == null) {
            return CommonResult.success(null);
        }
        RefundOrderDetailResp refundOrderDetailResp = cn.hutool.core.bean.BeanUtil.copyProperties(refundOrderDO, RefundOrderDetailResp.class);
        processOrder(refundOrderDetailResp);
        return CommonResult.success(refundOrderDetailResp);
    }

    @Operation(summary = "同步退款状态")
    @GetMapping("/status")
    CommonResult<Void> status(@RequestParam("refundOrderNo") String refundOrderNo) {
        refundOrderAppService.queryRefundStatus(refundOrderNo);
        return CommonResult.success();
    }

    @Operation(summary = "订单退款")
    @PostMapping("/create")
    CommonResult<RefundOrderResp> refundOrder(@Validated @RequestBody OrderRefundApplyReq adOrderRefundApplyReq) {
        RefundOrderParamReq refundOrderParamReq = new RefundOrderParamReq();
        refundOrderParamReq.setPayOrderNo(adOrderRefundApplyReq.getPayOrderNo());
        refundOrderParamReq.setAmount(adOrderRefundApplyReq.getRefundAmount());
        refundOrderParamReq.setReason(adOrderRefundApplyReq.getRefundReason());
        return refundOrderAppService.refundOrder(refundOrderParamReq);
    }
}
